package cn.claim.storage.tools;


import java.io.*;

public final class JSONTransportingLogger implements TransportingLogger {
    private final File target;

    /**@param target The transporting file that you need to <em>log for. Not the log file itself.</em>*/
    public JSONTransportingLogger(File target) {
        this.target = target;
    }

    @Override
    public void log(String md5, long length) {
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new File(target.getCanonicalPath() + ".jsonLog"));
            writer.println(new JSONTransportingData(md5, length).toJSON());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    @Override
    public TransportingData getData() {
        FileReader reader = null;
        try {
            File data = new File(target.getCanonicalPath() + ".jsonLog");
            if(!data.exists())
                return null;
            reader = new FileReader(data);
            return JSONParsable.parse(reader, JSONTransportingData.class);
        } catch (IOException ignored) {
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void removeDataFile() {
        try {
            File data = new File(target.getCanonicalPath() + ".jsonLog");
            //noinspection ResultOfMethodCallIgnored
            data.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //    public static void main(String[] args) {
//        JSONTransportingLogger logger = new JSONTransportingLogger(new File("./README.md"));
//        logger.log("xxxx",0);
//        System.out.println(logger.getData());
//    }
}
